package fi.vamk.android;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
public class register extends Activity implements View.OnClickListener {
	Button register;
	private EditText username;
	private EditText password;
	private EditText lastname;
	private EditText firstname;
	private EditText othername;
	private EditText phonenumber;
	private EditText email;
	private EditText regno;
	private EditText course;
	private EditText confirmPassword;
	private String[] departmentName;
	private String[] departmentId;
	private String[] levelName;
	private String[] levelId;
	public static Integer userId;
	public static String name;
	private Spinner department;
	private Spinner level;
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
    	super.onCreate(icicle);
    	setContentView(R.layout.register);
        register=(Button)findViewById(R.id.registerButton);
        username=(EditText)findViewById(R.id.username);
        password=(EditText)findViewById(R.id.password);
        lastname=(EditText)findViewById(R.id.lastname);
        firstname=(EditText)findViewById(R.id.firstname);
        othername=(EditText)findViewById(R.id.othername);
        email=(EditText)findViewById(R.id.email);
        phonenumber=(EditText)findViewById(R.id.phonenumber);
        regno=(EditText)findViewById(R.id.regno);
        confirmPassword=(EditText)findViewById(R.id.confirmpassword);
        course=(EditText)findViewById(R.id.course);
        department=(Spinner)findViewById(R.id.department);
        //department.setOnItemSelectedListener((OnItemSelectedListener) this);
        level=(Spinner)findViewById(R.id.level);
        //level.setOnItemSelectedListener((OnItemSelectedListener) this);
        register.setOnClickListener(this);
        String jsonDeptString = JSONParser.getJSONFromUrl(menu.IpAddress + "department.php").toString();
        String jsonLevelString = JSONParser.getJSONFromUrl(menu.IpAddress + "level.php").toString();
        JSONArray deptJson = null;
        JSONArray levelJson = null;
        try {
        	deptJson = new JSONArray(jsonDeptString);
        	levelJson = new JSONArray(jsonLevelString);
        } catch (JSONException je) {
           alertOkOnly("Json Exception" , je.getMessage().toString() );
            return;
        }
     JSONObject jsonDeptObject = null;
     JSONObject jsonlevelObject = null;
     ArrayList<String> arrayDepartmentIdList = new ArrayList<String>();
     ArrayList<String> arrayDeparmentNameList = new ArrayList<String>();
     ArrayList<String> arrayLevelIdList = new ArrayList<String>();
     ArrayList<String> arrayLevelNameList = new ArrayList<String>();
     for (int i = 0; i < deptJson.length(); i++) {
            try {
            	jsonDeptObject = deptJson.getJSONObject(i);
                    if(jsonDeptObject.has("id"))
                     {
                       String deptName = jsonDeptObject.getString("name");
                       String deptId = jsonDeptObject.getString("id");
                       arrayDepartmentIdList.add(deptId);
                       arrayDeparmentNameList.add(deptName);
                      }     

                 
            } catch (JSONException jee) {
                Log.e("TAG", "" + jee.getMessage());
            }

        }
     for (int i = 0; i < levelJson.length(); i++) {
         try {
         	jsonlevelObject = levelJson.getJSONObject(i);
                 if(jsonlevelObject.has("id"))
                  {
                    String levelName = jsonlevelObject.getString("name");
                    String levelId = jsonlevelObject.getString("id");
                    arrayLevelNameList.add(levelName);
                    arrayLevelIdList.add(levelId);
                   }     

              
         } catch (JSONException jee) {
             Log.e("TAG", "" + jee.getMessage());
         }

     }
    
        departmentName = arrayDeparmentNameList.toArray(new String[arrayDeparmentNameList.size()]);
        departmentId = arrayDepartmentIdList.toArray(new String[arrayDepartmentIdList.size()]);
        levelName = arrayLevelNameList.toArray(new String[arrayLevelNameList.size()]);
        levelId = arrayLevelIdList.toArray(new String[arrayLevelIdList.size()]);
       
        ArrayAdapter<String> deptArrayAdapter=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, departmentName);
        deptArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        department.setAdapter(deptArrayAdapter);
        ArrayAdapter<String> levelArrayAdapter=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, levelName);
        deptArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        level.setAdapter(levelArrayAdapter);
        }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.layout.menu_button, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
        case R.id.list:
        	startActivity(new Intent(register.this, menu.class));
         	finish();
         	return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }
    public void onItemSelected(AdapterView<?> parent,
    		View v, int position, long id) {
	    	
    		}
    		public void onNothingSelected(AdapterView<?> parent) {
    		}
    public void onClick(View view) {
	    	if (view == register)
	    	{
	    		String strUsername = username.getEditableText().toString();
	    		String strPassword = password.getEditableText().toString();
	    		String strLastname = lastname.getEditableText().toString();
	    		String strFirstname= firstname.getEditableText().toString();
	    		String strOthername = othername.getEditableText().toString();
	    		String strPhone = phonenumber.getEditableText().toString();
	    		String strEmail = email.getEditableText().toString();
	    		String strRegNo = regno.getEditableText().toString();
	    		String strCourse = course.getEditableText().toString();
	    		String strConfirmPassword = confirmPassword.getEditableText().toString();
	    		int deptIdPosition = department.getSelectedItemPosition();
	    		String deptId = departmentId[deptIdPosition].toString();
	    		int levelIdPosition = level.getSelectedItemPosition();
	    		String levId = levelId[levelIdPosition].toString();
	    		menu.name = username.getEditableText().toString();
	    		if( strUsername.equals("") || strPassword.equals("") || strLastname.equals("") || strFirstname.equals("") || strOthername.equals("") || strPhone.equals("") || strEmail.equals("") || strRegNo.equals("")||strCourse.equals("") || strConfirmPassword.equals("") ){
	    			//non field should be empty
	    			alertOkOnly("Registration Error","non field should be empty");
	    		}
	    		else
	    		{
	    			if (strPassword.equals(strConfirmPassword)){
	    				postRegisterData(strUsername, strPassword, strLastname, strFirstname, strOthername, strPhone, strEmail, strRegNo, strCourse, deptId, levId);
		    		}
		    		else{
		    			//password does not match
		    			alertOkOnly("Registration Error","password mismatch");
		    		}
	    		}
	    		
	    		
	    	}
    	}
    public void alertOkOnly(String title, String message)
    {
    	AlertDialog.Builder builder=
        	new AlertDialog.Builder(register.this);
        	builder
        	.setTitle(title)
        	.setMessage(message)
        	.setPositiveButton("OK", null)
        	.show();
    }
    public void postRegisterData( String username, String password, String lastname, String firstname, String othername, String phonenumber, String email, String regno, String course, String idDept, String idLevel ) {
        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(menu.IpAddress + "Register.php");
        //HttpPost httppost = new HttpPost("http://www.google.com");
        try {
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("username", username));
            nameValuePairs.add(new BasicNameValuePair("password", password));
            nameValuePairs.add(new BasicNameValuePair("lastname", lastname));
            nameValuePairs.add(new BasicNameValuePair("firstname", firstname));
            nameValuePairs.add(new BasicNameValuePair("othername", othername));
            nameValuePairs.add(new BasicNameValuePair("phonenumber", phonenumber));
            nameValuePairs.add(new BasicNameValuePair("email", email));
            nameValuePairs.add(new BasicNameValuePair("regno", regno));
            nameValuePairs.add(new BasicNameValuePair("course", course));
            nameValuePairs.add(new BasicNameValuePair("deptid", idDept ));
            nameValuePairs.add(new BasicNameValuePair("levelid", idLevel ));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);
            InputStream inputStream = response.getEntity().getContent();

            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);

            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            StringBuilder stringBuilder = new StringBuilder();

            String bufferedStrChunk = null;

            while((bufferedStrChunk = bufferedReader.readLine()) != null){
                stringBuilder.append(bufferedStrChunk);
            }
            if(Integer.parseInt(stringBuilder.toString()) > 0 ){
            	menu.userId = Integer.parseInt(stringBuilder.toString());
            	startActivity(new Intent(register.this, menuList.class));
	         	finish();
            	//setContentView(R.layout.menu);
            }else{
            	alertOkOnly("Registration Failed!", "Duplicate Entry, Please Contact the Administration"  );
            }
            
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
        	alertOkOnly("Exception!", e.toString()  );
        } catch (IOException e) {
            // TODO Auto-generated catch block
        	alertOkOnly("Exception!", e.toString()  );
        }
    } 
    }
